var express = require("express");
var router = express.Router();
var multer = require("multer");
var path = require("path");

var { Tribe, User, Post, Act } = require("../model/model");

//添加部落
router.post("/addTribe", (req, res) => {
  Tribe.create(req.body);
  res.send({
    status: 200,
    msg: "添加部落成功",
  });
});

//添加用户
router.post("/addUser", (req, res) => {
  User.create(req.body);
  res.send({
    status: 200,
    msg: "添加用户成功",
  });
});

//添加帖子
router.post("/addPost", (req, res) => {
  Post.create(req.body);
  res.send({
    status: 200,
    msg: "添加帖子成功",
  });
});

//添加活动
router.post("/addAct", (req, res) => {
  Act.create(req.body);
  res.send({
    status: 200,
    msg: "添加活动成功",
  });
});

//获取部落
router.get("/getTribe", async (req, res) => {
  let ls = await Tribe.find();
  res.send({
    status: 200,
    msg: "获取部落成功",
    ls,
  });
});

//获取帖子
router.get("/getPost", async (req, res) => {
  let { page = 1, limit = 2 } = req.query;
  let ls = await Post.find()
    .populate("userId")
    .populate("comments")
    .populate("tribeId")
    .skip((page - 1) * limit)
    .limit(limit);
  let count = await Post.countDocuments();
  res.send({
    status: 200,
    msg: "获取帖子成功",
    ls,
    count,
  });
});

//获取帖子详情
router.get("/getPostDetail", async (req, res) => {
  let id = req.query.id;
  let post = await Post.findById(id)
    .populate("userId")
    .populate("comments")
    .populate("tribeId");

  res.send({
    status: 200,
    msg: "获取帖子详情成功",
    post,
  });
});

//发送评论
router.post("/sendComment", async (req, res) => {
  let id = req.query.id;
  let post = await Post.findById(id);
  post.comments.push(req.body);
  await post.save();
  res.send({
    status: 200,
    msg: "评论成功",
  });
});

//获取活动
router.get("/getAct", async (req, res) => {
  let ls = await Act.find();
  res.send({
    status: 200,
    msg: "获取活动成功",
    ls,
  });
});

//获取活动详情
router.get("/getActDetail", async (req, res) => {
  let id = req.query.id;
  console.log(id);
  let act = await Act.findById(id);
  res.send({
    status: 200,
    msg: "获取活动详情成功",
    act,
  });
});

//获取所有部落
router.get("/getTribe", async (req, res) => {
  let ls = await Tribe.find();
  res.send({
    status: 200,
    msg: "获取部落成功",
    ls,
  });
});

// 配置存储路径和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "public/uploads/"); // 存储目录
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname)); // 文件名
  },
});

// 初始化 multer
const upload = multer({ storage: storage });

// 文件上传
router.post("/uploads", upload.single("file"), (req, res) => {
  res.send({
    status: 200,
    msg: "上传成功",
    url: "http://localhost:3000/uploads/" + req.file.filename,
  });
});

var { cateListModel, MvListModel, Comment } = require("../model/model");
var { User } = require("../model/model");
var jwt = require("jsonwebtoken");
var jwtSecret = "your_jwt_secret";
const { sendCode, randomCode } = require("../utils/phone");
const { secret, setAccessToken, setRefreshToken } = require("../utils/token");
var { User, Tribe, Message, AIMessage } = require("../model/model");
const socketIO = require("socket.io");
const { createServer } = require("http");
const httpServer = createServer();
/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});

router.post("/register", async (req, res) => {
  let { username, phone, password } = req.body;
  console.log(username, phone, password, "注册信息");

  let user = await User.findOne({ username });
  console.log(user, "user");

  if (!user) {
    await User.create({ username, phone, password });
    res.send({
      code: 200,
      msg: "注册成功",
    });
  } else {
    res.send({
      code: 401,
      msg: "用户名已存在",
    });
  }
  httpServer.listen(4000, () => {
    console.log("http服务已启动");
  });
  const io = socketIO(httpServer, {
    cors: {
      origin: "http://localhost:8080", //Vite 端口
      methods: ["GET", "POST"],
      credentials: true,
    },
  });
});

router.post("/getCode", (req, res) => {
  let phone = req.body.phone;
  console.log(phone, "1222");
  let code = randomCode(4);
  console.log(code);
  sendCode(phone, code, function (success) {
    if (success) {
      res.send({
        code1: 200,
        msg: "发送成功",
        data: code,
      });
    } else {
      res.send({
        code1: 500,
        msg: "发送失败",
      });
    }
  });
});

// 判断长token是否有效，刷新短token
router.get("/refresh", (req, res) => {
  // console.log(req,'zzreq');
  let r_tk = req.headers.refreshtoken;
  console.log(r_tk, "r_tk");

  // 解析token参数，token密钥，回调函数返回信息
  jwt.verify(r_tk, secret, (error) => {
    if (error) {
      res.send({
        code: 401,
        msg: "长token无效，请从新登录",
      });
    } else {
      // 如果长token有效则刷新两个token的保存时长
      res.send({
        code: 200,
        msg: "长token有效，返回新的token",
        accessToken: setAccessToken({ phone: "15127060858" }),
        refreshToken: setRefreshToken({ phone: "15127060858" }),
      });
    }
  });
});
// 引入qianfan SDK
var {
  ChatCompletion,
  setEnvVariable,
  Text2Image,
} = require("@baiducloud/qianfan");
// 使用安全认证AK/SK鉴权，通过环境变量初始化；替换下列示例中参数，安全认证Access Key替换your_iam_ak，Secret Key替换your_iam_sk
setEnvVariable("QIANFAN_ACCESS_KEY", "ALTAKKWcTq8mS0KdEOZEs80296");
setEnvVariable("QIANFAN_SECRET_KEY", "998ef223b7a94c82addd0ec2abf42142");
//创建一个ChatCompletion实例用来调用聊天接口
const client = new ChatCompletion();
//创建一个Text2Image实例用来调用文本转图片接口
const client2 = new Text2Image();
//接收AI回复的消息
let resultlist = "";

global.onlineUsers = new Map();

io.on("connection", (socket) => {
  console.log("socket.io connected:", socket.id);
  // 当有用户连接时，记录连接信息并将socket对象保存到全局变量中
  global.chatSocket = socket;
  // 当接收到添加用户事件时，将用户ID和对应的socket ID存储起来
  socket.on("add-user", (userId) => {
    onlineUsers.set(userId, socket.id);
    console.log("User added:", userId);
    console.log(global.onlineUsers, "onlineUsers");
  });
  //发送消息事件处理
  socket.on("send-msg", (data) => {
    const sendUserSocket = onlineUsers.get(data.to);
    if (sendUserSocket) {
      socket.to(sendUserSocket).emit("msg-receive", data.message); // 修改为 "msg-receive"
      console.log("Message sent:", data.message);
    }
  });

  //发送消息时触发
  socket.on("send", async (context) => {
    //当客户端发送"send"事件时，触发此事件
    try {
      console.log("开始处理请求");
      const resp = await client.chat(
        {
          messages: [
            {
              role: "user",
              content: context,
            },
          ],
          stream: true, //开启流式返回
        },
        "ERNIE-4.0-8K"
      );

      console.log("开始循环");
      for await (const chunk of resp) {
        if (chunk && chunk.result) {
          // 检查 chunk 是否有有效结果 chunk表示的是流式返回的数据
          // console.log(chunk.result);
          socket.emit("result", chunk.result); //将结果发送给客户端
          resultlist += chunk.result;
          console.log(resultlist);
          await AIMessage.create({ fromSelf: false, message: resultlist });
        }
      }
    } catch (err) {
      console.error("处理请求时发生错误:", err);
    }
  });
});

router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username, password });
  // console.log(user);
  if (user) {
    res.send({ code: 200, msg: "登录成功", user });
  }
});

//获取所有联系人
router.get("/allUsers", async (req, res) => {
  const id = req.query.id;
  const page = req.query.page;
  const limit = req.query.limit;
  const users = await User.find({ _id: { $ne: id } })
    .select(["_id", "username", "avatar"])
    .skip((page - 1) * limit)
    .limit(limit);
  res.send({
    code: 200,
    data: users,
  });
});

//添加消息
router.post("/addMessage", async (req, res) => {
  try {
    const { from, to, message } = req.body;
    console.log(from, to, message, "添加");
    const data = await Message.create({
      message: { text: message },
      users: [from, to],
      sender: from,
    });
    if (data) return res.send({ msgs: "发送成功" });
    return res.send({ msg: "发送失败" });
  } catch (err) {
    console.log(err);
  }
});

//获取消息列表
router.post("/getMessageList", async (req, res) => {
  try {
    const { from, to } = req.body;
    const messages = await Message.find({
      //通过users数组中的元素是否包含from和to来查询
      users: {
        $all: [from, to],
      },
    }).sort({ updateAt: 1 });
    //通过sort方法，将messages按照updateAt字段进行更新
    const projectMessages = messages.map((message) => {
      return {
        //通过message.sender.toString()获取发送者的id
        fromSelf: message.sender.toString() === from,
        //通过message.message.text获取消息内容
        message: message.message.text,
      };
    });
    res.send({ code: 200, data: projectMessages });
    // console.log(projectMessages);
  } catch (err) {
    console.log(err);
  }
});

router.post("/login", async (req, res) => {
  const { phone, codeValue } = req.body;
  console.log(phone, codeValue, "phone,code");
  const user = await User.findOne({ phone });
  if (user) {
    res.send({
      code: 200,
      user: user,
      codeValue,
      data: {
        accessToken: setAccessToken({ phone: phone }),
        refreshToken: setRefreshToken({ phone: phone }),
      },
    });
  } else {
    res.send({
      code: 401,
      msg: "Invalid credentials",
    });
  }
});

router.post("/test", async (req, res) => {
  const phone = "17531323931";
  res.send({
    code: 200,
  });
  //获取AI回复消息
  router.get("/resolveQuestion", async (req, res) => {
    const { context } = req.query;
    await AIMessage.create({ fromSelf: true, message: context });
    res.send({
      code: 200,
      resultlist,
    });
  });
});

router.post("/resolveImage", async (req, res) => {
  const { prompt } = req.body;
  console.log(prompt);
  const resp = await client2.text2Image(
    {
      prompt: prompt,
    },
    "Stable-Diffusion-XL"
  );

  const base64Image = resp.data[0].b64_image;
  // 创建一个简单的服务器

  let html = `<img src="data:image/jpeg;base64,${base64Image}" style="width:200px;height:200px;"/><br/>`;
  res.send({
    code: 200,
    html,
  });
});
var express = require('express');
var router = express.Router();
var { Release, MvListModel } = require('../model/model')
const AlipayFormData = require('alipay-sdk/lib/form').default
const alipaySdk = require('./alipay')
let multiparty = require('multiparty')
/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});


//-----------------高兴旺-----------------

// ----------------支付宝沙箱------------
// 生成随机数
function randomCode() {
  var code = "";
  var codeLength = 7;
  var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
  for (var i = 0; i < codeLength; i++) {
    var index = Math.floor(Math.random() * 10);
    code += random[index];
  }
  return code;
}
router.post('/pcpay', async (req, res) => {
  let form = req.body
  const formData = new AlipayFormData()
  formData.setMethod('get');
  // 通过addField增加参数
  // 在用户支付完成之后，支付宝服务器会根据传入的notify_url,以post请求的形式将支付结果作为参数通知到商户系统
  // 支付成功或失败都返回
  formData.addField('returnUrl', "http://localhost:8080/shudong");// 支付成功后跳转的地址
  formData.addField('bizContent', {
      out_trade_no: randomCode(),//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
      product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
      total_amount: form.price,// 订单总金额
      subject: form.name,// 订单描述
      body: form.name,// 商品描述
  })
  // 返回promise
  const result = await alipaySdk.exec(
      'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
      {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
      { formData: formData }// result为可以跳转支付链接的url
  )
  // res.json({ url: result })
  res.send({
    code:200,
    result
  })

})




// ----------------用户头像----------------
router.post("/uploadImg", (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (err, fields, files) => {
    res.send({
      path: 'http://localhost:3000/' + files.file[0].path
    })
  })
})
// --------------------留言板--------------------
router.post("/addRelease", (req, res) => {
  Release.create(req.body)
  res.send({
    code: 200
  })
})

// --------------------获取留言审核状态-------------------
router.get("/getReleaseStatus", async (req, res) => {
  let Rels = await Release.find()
  res.send({
    code: 200,
    Rels
  })
})

router.post("/updateReleaseStatus", async (req, res) => {
  let { id } = req.query
  await Release.updateOne({ _id: id }, { release: true })
  res.send({
    code: 200
  })
})

router.post("/updateReleaseStatus1", async (req, res) => {
  let { id } = req.query
  await Release.updateOne({ _id: id }, { release: false })
  res.send({
    code: 200
  })
})

// ----------------收藏数据获取--------------------
router.get("/getCollect", async (req, res) => {
  let { page, pagesize } = req.query
  let colleatls = await MvListModel.find().skip((page - 1) * pagesize).limit(pagesize)
  let total = await MvListModel.find().countDocuments()
  res.send({
    code: 200,
    colleatls, total
  })
})

//-----------------高兴旺-----------------

module.exports = router;
